<template>
    <view class="freeAppraisal">
        <view class="freeAppraisal_pding">
            <view class="freeAppraisal_tebcll">
                <view class="freeAppraisal_xiala">
                    <picker bindchange="bindAccountChange" mode='selector' value="{{accountIndex}}" range="{{accounts}}" disabled="{{could}}" @tap="disabledTap()">
                        <view class="weui-select">{{accountIndex===null ? '请选择品牌' : accounts[accountIndex]}}</view>
                    </picker>
                </view>
                <view class="freeAppraisal_shuru"><input type="text" placeholder="标识鉴定物品的名称" value="{{goodName}}" bindinput="bindKeyGoodname" disabled="{{could}}" @tap="disabledTap()"></view>
            </view>
            <!--//文本框-->
            <view class=" weui-cells_after-title">
                <view class="weui-cell">
                    <view class="weui-cell__bd">
                        <textarea class="weui-textarea" placeholder="添加内容（选填）" value="{{goodContent}}" bindinput="bindKeyGoodcontent" disabled="{{could}}" @tap="disabledTap()"/>
                        <!--<view class="weui-textarea-counter">0/200</view>-->
                    </view>
                </view>
            </view>
            <!--//上传图片-->
            <view class="weui-uploader">
                <view class="weui-uploader__bd">
                    <view class="weui-uploader__input-box" style="background:url({{pic1 ? pic1 : 'https://gatherabc.oss-cn-qingdao.aliyuncs.com/xcx/publish/upa.png'}}) no-repeat center center / 100% 100%">
                        <view class="weui-uploader__input" bindtap="chooseImage(1)"></view>
                    </view>
                    <view class="weui-uploader__input-box" style="background:url({{pic2 ? pic2 : 'https://gatherabc.oss-cn-qingdao.aliyuncs.com/xcx/publish/upb.png'}}) no-repeat center center / 100% 100%">
                        <view class="weui-uploader__input" bindtap="chooseImage(2)"></view>
                    </view>
                    <view class="weui-uploader__input-box" style="background:url({{pic3 ? pic3 : 'https://gatherabc.oss-cn-qingdao.aliyuncs.com/xcx/publish/upg.png'}}) no-repeat center center / 100% 100%">
                        <view class="weui-uploader__input upload_3" bindtap="chooseImage(3)"></view>
                    </view>
                    <view class="weui-uploader__input-box" style="background:url({{pic4 ? pic4 : 'https://gatherabc.oss-cn-qingdao.aliyuncs.com/xcx/publish/upd.png'}}) no-repeat center center / 100% 100%">
                        <view class="weui-uploader__input upload_4" bindtap="chooseImage(4)"></view>
                    </view>
                    <view class="weui-uploader__input-box" style="background:url({{pic5 ? pic5 : 'https://gatherabc.oss-cn-qingdao.aliyuncs.com/xcx/publish/upe.png'}}) no-repeat center center / 100% 100%">
                        <view class="weui-uploader__input upload_5" bindtap="chooseImage(5)"></view>
                    </view>
                    <view class="weui-uploader__input-box" style="background:url({{pic6 ? pic6 : 'https://gatherabc.oss-cn-qingdao.aliyuncs.com/xcx/publish/upf.png'}}) no-repeat center center / 100% 100%">
                        <view class="weui-uploader__input upload_6" bindtap="chooseImage(6)"></view>
                    </view>
                    <view class="weui-uploader__input-box" wx:for="{{files}}" wx:key="*this" id="{{item}}">
                        <image class="weui-uploader__img" src="{{item}}" mode="aspectFit" />
                    </view>
                    <view class="weui-uploader__input-box" style="background:url('https://gatherabc.oss-cn-qingdao.aliyuncs.com/xcx/publish/upc.png') no-repeat center center / 100% 100%">
                        <view class="weui-uploader__input upload_7" bindtap="chooseImage(7)"></view>
                    </view>
                </view>
            </view>

            <view class="gongxi">
                <view class="huang" bindtap="commit">提交</view>
            </view>
        </view>
        <navigator url="/pages/appraisal/guide" class="weui-cell weui-cell_access zhinan" hover-class="weui-cell_active" style="position: static; background:#fff">
            <view class="weui-cell__hd">
                <image src="https://gatherabc.oss-cn-qingdao.aliyuncs.com/xcx/newsInfo.png" style="margin-right: 5px;vertical-align: middle;width:20px; height: 20px;"></image>
            </view>
            <view class="weui-cell__bd">新手指南</view>
            <view class="weui-cell__ft weui-cell__ft_in-access"></view>
        </navigator>
        <view class="freeAppraisal_foot">也可以上传购买交易截图，辅助鉴别</view>
    </view>
</template>
<script>
    import wepy from 'wepy'
    import api from '@/api/api'
    import utils from '@/utils/utils'
    import tip from '@/utils/tip'
    import {USER_INFO, USER_SPECICAL_INFO, USER_ID} from '@/utils/constant'

    export default class freeAppraisal extends wepy.page {
      config = {
        // 配置当前页面
        navigationBarTitleText: '发布' // 头部标题
      }
      components = {}

      data = {
        could:false,
        myid:'',
        avatarUrl: '',
        nickName: '',
        bShowBind: false,
        brands: [],
        accounts: [],
        accountIndex: null,
        goodName: '',
        allFiles: [],
        files: [],
        goodContent: '',
        policyInfo: '',
        type: '',
        pic1: '',
        pic2: '',
        pic3: '',
        pic4: '',
        pic5: '',
        pic6: ''
      }

      async getRootCateTopLevel() {
        let self = this
        api.goodsBrandSearch().then(function(res) {
          if (res.data.code == 0) {
            self.brands = res.data.data
            for (let item of res.data.data) {
              self.accounts.push(item.name)
            }
            self.$apply()
          } else {
            tip.error(res.data.msg)
          }
        })
      }

      async ientityByType(type, key) {
        let self = this
        let userID = wepy.getStorageSync(USER_ID) || ''
        api
          .commitIdentify({
            method: 'POST',
            query: {
              brandId: self.brands[self.accountIndex].id,
              content: self.goodContent,
              cdkey: key ? key : '',
              couponId: '',
              free: +type,
              images: self.allFiles.join(','),
              name: self.goodName,
              userId: userID
            }
          })
          .then(function(res) {
            if (res.data.code == 0) {
              // self.goodContent = '';
              // self.allFiles = [];
              // self.accountIndex = null;
              // self.goodName = '';
              wepy.navigateTo({
                url: '/pages/appraisal/ReleaseCompletion'
              })
            } else {
              tip.error(res.data.msg)
            }
            self.$apply()
          })
      }

      async upload_pic(key) {
          let self = this;
          let userID = wepy.getStorageSync(USER_ID) || '';
          const a = await api.uploadAgain({
              method:'POST',
              query:{
                  content:self.goodContent,
                  id:key,
                  userId: userID,
                  images :self.allFiles.join(',')
              }
          })
          if (a.data.code == 0) {
            wepy.navigateBack()
          }else{
            tip.error(a.data.msg)
          }
      }

      async commitData() {
        let self = this
        let userID = wepy.getStorageSync('userId') || ''
        // type为2付费发布，否则免费发布
        if (self.type == '2') {
          self.ientityByType(2, self.mykey)
        } else if(self.type == '1'){
          self.ientityByType(1)
        } else if(self.type == '3'){
          self.upload_pic(self.myid)
        }
      }

      /**
       * web端上传文件获取上传policy
       * @returns {Promise<void>}
       */
      async policyFun() {
        const t = this
        let a = await api.getWebPolicy()
        if (a.data.code == 0) {
          t.policyInfo = a.data.data
        } else {
          tip.error(a.data.msg)
        }
        t.$apply()
      }


      async getDetailFalse() {
          let self = this
          const json = await api.queryIdentifyId({}, self.myid)
          if (json.data.code == 0) {
              self.goodName = json.data.data.goodsName;
              self.accountIndex = self.accounts.indexOf(json.data.data.brandName);
              self.goodContent = json.data.data.content;
              self.allFiles = json.data.data.images.split(',');
              self.pic1 = self.allFiles[0];
              self.pic2 = self.allFiles[1];
              self.pic3 = self.allFiles[2];
              self.pic4 = self.allFiles[3];
              self.pic5 = self.allFiles[4];
              self.pic6 = self.allFiles[5];
              self.files = self.allFiles.slice(6);
              self.$apply()
          }
      }

      onLoad(option) {
        this.getRootCateTopLevel()
        this.type = option.type;
        this.mykey = option.mykey;
        this.myid = option.id;
        if(option.type == "3"){
          this.could = true;
          this.getDetailFalse()
        }
      }

      onShow() {
        // this.goodContent = '';
        // this.allFiles = [];
        // this.files = [];
        // this.accountIndex = null;
        // this.goodName = '';
      }

      methods = {
        // 方法
        disabledTap(){
          if(this.could){
            console.log("####")
            tip.toast('该数据不可修改', null, 'none');
          }
        },
        bindAccountChange(e) {
          this.accountIndex = +e.detail.value
        },
        bindKeyGoodname(e) {
          this.goodName = e.detail.value
        },
        bindKeyGoodcontent(e) {
          this.goodContent = e.detail.value
        },
        commit() {
          if (this.accountIndex === null) {
            return tip.toast('请选择品牌', null, 'none')
          } else if (!this.goodName) {
            return tip.toast('请输入标识鉴定物名称', null, 'none')
          } else if (!this.allFiles.length) {
            return tip.toast('请上传图片', null, 'none')
          } else if (
            !this.allFiles[0] ||
            !this.allFiles[1] ||
            !this.allFiles[2] ||
            !this.allFiles[3] ||
            !this.allFiles[4] ||
            !this.allFiles[5]
          ) {
            return tip.toast('前六张图片必须上传', null, 'none')
          }
          this.commitData()
        },
        chooseImage: function(k) {
          var that = this
          wx.chooseImage({
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function(res) {
              let name = 'wxImage' + Date.parse(new Date()) + '.png'
              wx.uploadFile({
                url: 'https://gatherapi.haomengpeifang.com/aliyun/oss/upload',
                filePath: res.tempFilePaths[0],
                name: 'file',
                success: function(req) {
                  let r
                  if (typeof req.data == 'string') {
                    r = JSON.parse(req.data)
                  } else {
                    r = req
                  }
                  if (r.code == 0) {
                    switch (k) {
                      case '1':
                        that.pic1 = r.data[0]
                        that.allFiles[0] = that.pic1
                        break

                      case '2':
                        that.pic2 = r.data[0]
                        that.allFiles[1] = that.pic2
                        break

                      case '3':
                        that.pic3 = r.data[0]
                        that.allFiles[2] = that.pic3
                        break

                      case '4':
                        that.pic4 = r.data[0]
                        that.allFiles[3] = that.pic4
                        break

                      case '5':
                        that.pic5 = r.data[0]
                        that.allFiles[4] = that.pic5
                        break

                      case '6':
                        that.pic6 = r.data[0]
                        that.allFiles[5] = that.pic6
                        break

                      default:
                        that.files = that.files.concat(r.data[0])
                        that.allFiles.concat(...that.files)
                        break
                    }
                    that.$apply()
                  } else {
                    tip.error(r.msg)
                  }
                }
              })
            }
          })
        },
        previewImage: function(e) {
          wx.previewImage({
            current: e.currentTarget.id, // 当前显示图片的http链接
            urls: this.files // 需要预览的图片http链接列表
          })
        }
      }
      events = {}
    }
</script>
<style lang="less">
.freeAppraisal {
    background: #fff;
    height: 100vh;
    .freeAppraisal_pding {
        padding: 30rpx 30rpx;

        .freeAppraisal_tebcll {
            .freeAppraisal_xiala {
                width: 260rpx !important;
                display: table-cell;
                background: #e3e3e3;
                border-radius: 6rpx;
                .weui-select {
                    border-right: 0;
                }
            }
            .freeAppraisal_shuru {
                display: table-cell;
                background: #e3e3e3;
                width: 400rpx;
                position: relative;
                left: 30rpx;
                border-radius: 6rpx;
                input {
                    margin: 0 20rpx;
                    border-left: 1px solid #acacac;
                    padding-left: 20rpx;
                    line-height: 1.5rem;
                }
            }
        }

        .gongxi {
            padding: 60rpx 0;
            .huang {
                background: #ffb60b;
            }
            > view {
                width: 90%;
                margin: 0 auto;
                height: 70rpx;
                text-align: center;
                line-height: 70rpx;
                color: #fff;
                border-radius: 5rpx;
            }
        }

        .weui-cells_after-title {
            border: 1px solid #ddd;
            margin-top: 40rpx;
            .weui-cell {
                height: 300rpx;
                .weui-cell__bd {
                    height: 300rpx;
                    .weui-textarea {
                        height: 250rpx;
                    }
                }
            }
        }
        .weui-uploader {
            padding: 40rpx 0;
            .weui-uploader__input-box:after,
            .weui-uploader__input-box:before {
                content: none;
            }
            .weui-uploader__input-box {
                margin-right: 13rpx;
            }
            .weui-uploader__input-box:nth-child(4n) {
                margin-right: 0;
            }
            .upload_1 {
                background: red;
            }
        }
    }
    .zhinan {
        border-top: 1px solid #ddd;
        border-bottom: 1px solid #ddd;
    }
    .freeAppraisal_foot {
        text-align: center;
        padding-top: 60rpx;
        padding-bottom: 40rpx;
        color: #999;
        background: #fff;
    }
    .weui-uploader__file {
        width: 144rpx;
        height: 144rpx;
        image {
            width: 100%;
            height: 100%;
            border: solid 1px #cccccc;
            box-sizing: border-box;
        }
    }
}
</style>
